package com.example.datatrans.util;


import java.io.*;
import java.security.MessageDigest;

/**
 * @author: cs
 * @date: 2024-10-29 15:43:33
 * @since: 1.0
 */
public class FileUtils {

    private static byte[] createChecksum(InputStream fis) throws Exception {
        byte[] buffer = new byte[1024];
        MessageDigest complete = MessageDigest.getInstance("MD5"); //如果想使用SHA-1或SHA-256，则传入SHA-1,SHA-256
        int numRead;

        do {
            numRead = fis.read(buffer);    //从文件读到buffer，最多装满buffer
            if (numRead > 0) {
                complete.update(buffer, 0, numRead);  //用读到的字节进行MD5的计算，第二个参数是偏移量
            }
        } while (numRead != -1);

        fis.close();
        return complete.digest();
    }

    public static String generateHashCode(File file) throws Exception {
        InputStream inputStream = new FileInputStream(file);
        byte[] b = createChecksum(inputStream);
        String result = "";

        for (int i = 0; i < b.length; i++) {
            result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);//加0x100是因为有的b[i]的十六进制只有1位
        }
        return result;
    }


    public static byte[] readFile2ByteArray(File file) throws IOException {
        long fileSize = file.length();
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[(int) fileSize];
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length && (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
            offset += numRead;
        }
        if (offset != buffer.length) {
            System.err.println("文件未读取完成");
        }
        fis.close();
        return buffer;
    }

}
